﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;

namespace EnhancedSolutions.Admin.BramNuyts.EnhancedSolutions
{
    public partial class DownloadSolutions : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Btn_Ok_Click(object sender, EventArgs e)
        {
            bool selectedItems = false;

            ExtractedSolutionList solList = new ExtractedSolutionList();
            foreach (ListItem item in ((SolutionsCheckBoxList)DownloadSolutionsList).Items)
            {
                if (item.Selected)
                {
                    selectedItems = PrepareSolutionFile(selectedItems, solList, item);
                }
            }

            if (selectedItems)
            {
                CreateZip(solList);
            }
        }

        /// <summary>
        /// Prepares the solution file.
        /// </summary>
        /// <param name="selectedItems">if set to <c>true</c> [selected items].</param>
        /// <param name="fileLocations">The file locations.</param>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        private bool PrepareSolutionFile(bool selectedItems, ExtractedSolutionList solList, ListItem item)
        {
            selectedItems = true;
            ExtractedSolution oSolution = new ExtractedSolution(item.Value);
            oSolution.Extract();
            solList.Add(oSolution);
            return selectedItems;
        }

        /// <summary>
        /// Creates the zip.
        /// </summary>
        /// <param name="fileLocations">The file locations.</param>
        private void CreateZip(ExtractedSolutionList solList)
        {
            string fileName = String.Format("{0}.zip", System.Guid.NewGuid().ToString());
            Response.Clear();
            Response.ClearHeaders();
            Response.ContentType = "application/zip";
            Response.AddHeader("content-disposition", "filename=" + fileName);

            string zipPath = Helper.GetTemporaryPath(fileName);
            Zipper zip = new Zipper(zipPath, solList);
            if (zip.CreateZipFile())
            {
                Response.TransmitFile(zipPath);
            }
            Response.Flush();
            Response.End();
            solList.RemoveAll();
            File.Delete(zipPath);
        }
    }
}
